<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <!-- <button @click="type = 1">btn1</button>
      <button @click="type = 2">btn2</button>
      <button @click="type = 3">btn3</button>

      <hr />
      
      <Child1 v-if="type === 1"></Child1>
      <Child2 v-if="type === 2"></Child2>
      <Child3 v-if="type === 3"></Child3> -->

      <!-- 动态组件 -->
      <!-- 必须要配合is属性, is的属性值是组件的名称 -->
      <button @click="componentName = 'Child1'">btn1</button>
      <button @click="componentName = 'Child2'">btn2</button>
      <button @click="componentName = 'Child3'">btn3</button>
      <hr />

      <!-- 
        keep-alive叫缓存组件 
        当动态组件切换的时候不要销毁和重新创建
      -->
      <keep-alive>
        <component :is="componentName"></component>
      </keep-alive>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const Child1 = {
        template: `
          <div>这是child1子组件</div>
        `,
      };

      let timer;
      // 被动态组件切换的组件默认是会被销毁和重新创建的
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>这是child2子组件 - {{ count }} - <button @click="count++">btn</button></div>
        `,
        mounted() {
          console.log("child2组件被挂载了");
          // timer = setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child2组件被销毁了");
        },
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
        activated() {
          console.log("child2 activated");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件从 DOM 中被移除时调用。
        deactivated() {
          console.log("child2 deactivated");
          clearInterval(timer);
        },
      };

      const Child3 = {
        template: `
          <div>这是child3子组件</div>
        `,
      };

      Vue.createApp({
        data() {
          return {
            // type: 1,
            componentName: "Child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      }).mount("#app");
    </script>
  </body>
</html>
